package org.udp;

import java.io.IOException;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
 * 基于udp的客户端
 */
public class UDPEchoClient {
    //声明一个DatagramSocket对象
    private DatagramSocket socket;
    //声明服务器的IP
    private String serverIp;
    //声明服务器的端口号
    private int serverPort;

    //通过构造方法指定服务器的IP和端口号
    public UDPEchoClient(String serverIp, int serverPort) throws SocketException {
        //初始化DatagramSocket对象
        this.socket = new DatagramSocket();
        //指定服务器的IP和端口号
        this.serverIp = serverIp;
        this.serverPort = serverPort;
    }

    /**
     * 客户端服务
     */
    public void start() throws IOException {
        System.out.println("客户端已启动。");
        //循环处理客户端输入
        while(true) {
            System.out.println("-->");
            Scanner scanner = new Scanner(System.in);
            //1.获取用户输入
            String request = scanner.nextLine();
            if(request == null || request.isEmpty()) {
                System.out.println("输入不能为空");
                continue;
            }
            //2.创建目标的SocketAddress对象
            SocketAddress address = new InetSocketAddress(serverIp, serverPort);
            //3.定义一个用于包装用户请求数据的DatagramPaket
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(StandardCharsets.UTF_8),
                    0,request.getBytes().length,address);
            //4.发送真实的数据到服务器
            socket.send(requestPacket);
            // 5. 用DatagramPacket接收服务器的响应的数据
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024], 1024);
            //6.接收数据
            socket.receive(responsePacket);
            //7.解析数据得到响应
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength(), "UTF-8");
            // 8. 打印响应结果
            System.out.printf("request = %s, response = %s\n", request, response);

        }
    }
    public static void main(String[] args) throws IOException {
        UDPEchoClient client = new UDPEchoClient("127.0.0.1", 8888);
        client.start();
    }
}
